对称加密算法实现(通常是加密web.config)
/// <summary>
/// 加密解密类
/// </summary>
public class EncryptAndDescrypt
{
private SymmetricAlgorithm myjl;//表示所有对称算法的实现都必须从中继承的抽象基类。
private const string CIV = "abceftjp152=";//密钥
private const string CKEY = "Acefslqbqjs=";//初始化向量
/// <summary>
/// 生成加密解密类
/// </summary>
public EncryptAndDescrypt()
{
myjl = new DESCryptoServiceProvider();//定义访问数据加密标准 (DES) 算法的加密服务提供程序 (CSP) 版本的包装对象。 此类不能被继承
}
/// <summary>
/// 通过对称算法进行加密
/// </summary>
/// <param name="value">要加密的字符串</param>
/// <returns></returns>
public string EncryptString(string value)
{
ICryptoTransform ct;//定义基本的加密运算符
MemoryStream ms;
CryptoStream cs;//定义将数据流转链接到加密转换的流
byte[] byt;
//CreateEncryptor创建加密对象
ct = myjl.CreateEncryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV));
byt = Encoding.UTF8.GetBytes(value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// 解密算法
/// </summary>
/// <param name="value">输入要解密的字符</param>
/// <returns></returns>
public String DescrptyString(string value)
{
//定义基本的加密转换运算
ICryptoTransform ct;
MemoryStream ms;
CryptoStream cs;
byte[] byt;
ct = myjl.CreateDecryptor(Convert.FromBase64String(CKEY), Convert.FromBase64String(CIV));
byt = Convert.FromBase64String(value);
ms = new MemoryStream();
cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
cs.Write(byt, 0, byt.Length);
cs.FlushFinalBlock();
cs.Close();
return Encoding.UTF8.GetString(ms.ToArray());
}
}